package org.sam.swing.builder;

import java.awt.Component;
import java.awt.Container;

import javax.swing.Spring;
import javax.swing.SpringLayout;
import javax.swing.SpringLayout.Constraints;

/**
 * 生成layout布局的工具类
 * 
 * @author sam
 *
 */
public class SpringLayoutBuiler extends AbstractFixedLayoutBuilder  {
	
	/**
	 * 生成layout布局的工具类
	 * @param parent
	 */
	public SpringLayoutBuiler(Container parent) {
		super(parent);
	}

	/**
	 * 当前的布局对象
	 */
	protected SpringLayout layout;

	/**
	 * 初始化系统参数
	 */
	@Override
	protected void init() {
		this.yLine = -1;
		if (this.parent != null) {
			layout = new SpringLayout();
			this.parent.setLayout(layout);
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void append(Component component) {
		if (this.parent == null)
			throw new RuntimeException("parent container is null");

		if (this.layout == null)
			throw new RuntimeException("layout container is null");

		// 实现一个空间的方法
		int y = this.getAndSetNextYLine();

		// 标签控件
		Constraints labelConstraints = layout.getConstraints(component);
		labelConstraints.setX(Spring.constant(this.xLabelLine));
		labelConstraints.setY(Spring.constant(y));
		labelConstraints.setHeight(Spring.constant(this.editorHeight));
		layout.putConstraint(SpringLayout.EAST, component, -rightSpace, SpringLayout.EAST, this.parent);
		this.parent.add(component);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void append(Component lable, Component editor) {
		if (this.parent == null)
			throw new RuntimeException("parent container is null");

		if (this.layout == null)
			throw new RuntimeException("layout container is null");

		if (lable == null || editor == null)
			throw new RuntimeException("not support components length");

		// 暂时实现一个label和一个editor的方式
		int y = this.getAndSetNextYLine();

		// 标签控件
		Constraints labelConstraints = layout.getConstraints(lable);
		labelConstraints.setX(Spring.constant(this.xLabelLine));
		labelConstraints.setY(Spring.constant(y));
		labelConstraints.setWidth(Spring.constant(lblWidth));
		labelConstraints.setHeight(Spring.constant(this.editorHeight));
		this.parent.add(lable);

		// 编辑控件·
		Constraints editorConstraints = layout.getConstraints(editor);
		editorConstraints.setX(Spring.constant(this.xEditorLine));
		editorConstraints.setY(Spring.constant(y - offset));
		editorConstraints.setHeight(Spring.constant(this.editorHeight));
		layout.putConstraint(SpringLayout.EAST, editor, -rightSpace, SpringLayout.EAST, this.parent);
		this.parent.add(editor);
	}

}
